package com.discuz.post;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Login {

	private static String domain;
	
	public static boolean loginSite(String domain,String u,String p) throws ClientProtocolException, IOException {

		
		// get login formhash
		String loginFormhash = getFormHash(domain);

		// send login request
		String loginURL = domain + "member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes";
		HttpPost httpost = new HttpPost(loginURL);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("username",u));
		nvps.add(new BasicNameValuePair("password",p));
		nvps.add(new BasicNameValuePair("formhash", loginFormhash));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, "GB2312"));
		HttpResponse response = HttpUtils.get().execute(httpost);
		
		HttpEntity entity = response.getEntity();
		String c = EntityUtils.toString(entity);
		EntityUtils.consume(entity);
		if (c.contains("设置") && c.contains("退出") || (c.contains("Setting") && c.contains("message"))) {
			System.out.println("login succeed.....");
			return true;
		}
		return false;
		
	}
	
	
	private static String getFormHash(String url) {

		HttpGet httpget = new HttpGet(url);
		String entityString = null;
		try {
			HttpResponse response = HttpUtils.get().execute(httpget);
			HttpEntity entity = response.getEntity();
			entityString = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		String loginFormhash = null;
		int pos = entityString.indexOf("name=\"formhash\" value=");
		loginFormhash = entityString.substring(pos + 23, pos + 23 + 8);

		return loginFormhash;
	}
}
